function Promise(executor) {
    this.PromiseState = 'pending';
    this.PromiseResult = undefined;
    this.callbacks = [];
    const resolve = (value) => {
        if (this.PromiseState !== 'pending') return;
        this.PromiseState = 'fulfilled';
        this.PromiseResult = value;
        if (this.callbacks.length) {
            this.callbacks.forEach(item => {
                item.success();
            })
        }
    }
    const reject = (reason) => {
        if (this.PromiseState !== 'pending') return;
        this.PromiseState = 'rejected';
        this.PromiseResult = reason;
        if (this.callbacks.length) {
            this.callbacks.forEach(item => {
                item.fail();
            })
        }
    }
    try {
        executor(resolve, reject);
    } catch (e) {
        reject(e);
    }
}
Promise.prototype.then = function (onResolve, onReject) {
    return new Promise((resolve, reject) => {
        if (this.PromiseState === 'fulfilled') {
            let rs = onResolve(this.PromiseResult);
            // 1. rs 是非Promise对象，那么成功Promise，返回的结果就是成功Promise的结果值
            // 2. rs 是Promise对象，你成功我也成功，你成功的结果就是我成功的结果。你失败我也失败，你失败的结果也是我失败的结果
            if(rs instanceof Promise){// rs 是Promise
                rs.then(value=>{
                    resolve(value)
                },reason=>{
                    reject(reason);
                })
            }else{// rs不是Promise
                resolve(rs);
            }
        }
        if (this.PromiseState === 'rejected') {
            let rs = onReject(this.PromiseResult);
            if(rs instanceof Promise){
                rs.then(resolve,reject)
            }else{
                resolve(rs);
            }
        }
        if (this.PromiseState === 'pending') {
            this.callbacks.push({
                success: () => {
                    let rs = onResolve(this.PromiseResult);
                    if(rs instanceof Promise){
                        rs.then(resolve,reject)
                    }else{
                        resolve(rs);
                    }
                },
                fail: () => {
                    let rs = onReject(this.PromiseResult);
                    if(rs instanceof Promise){
                        rs.then(resolve,reject)
                    }else{
                        resolve(rs);
                    }
                }
            })
        }
    })
}